﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KeyboardImageViewer
{
    public static class TagOperations
    {
        public static void UpdateCurrentTags(List<string> oldTags, List<string> newTags)
        {
            Database.SetTags(ImageManager.Connection, newTags, ImageListControl.CurrentImageId, ImageManager.Config.TagDependencies, oldTags);

            ImageManager.MainForm.UpdateInfoBar();
        }

        public static void AddTagToVisible(string tags)
        {
            string firstTag = GetFirstTag(tags);

            if (!firstTag.Contains("|") && firstTag != "")
            {
                Database.AddTagToImages(ImageManager.Connection, firstTag, ImageListControl.ImageList, ImageManager.Config.TagDependencies);

                ImageManager.MainForm.UpdateInfoBar();
            }
        }

        public static void RemoveTagFromVisible(string tags)
        {
            string firstTag = GetFirstTag(tags);

            if (firstTag != null)
            {
                Database.RemoveTagFromImages(ImageManager.Connection, firstTag, ImageListControl.ImageList, ImageManager.Config.TagDependencies);

                ImageManager.MainForm.UpdateInfoBar();
            }
        }

        public static void RenameTag(string oldTag, string newTag)
        {
            Database.RenameTag(oldTag, newTag, ImageManager.Config.TagDependencies, ImageManager.Connection);
            Database.RebuildTagsSummary();

            ImageManager.MainForm.UpdateInfoBar();
        }

        public static void DeleteTag(string tagToDelete)
        {
            Database.DeleteTag(tagToDelete, ImageManager.Config.TagDependencies, ImageManager.Connection);
            Database.RebuildTagsSummary();

            ImageManager.MainForm.UpdateInfoBar();
        }

        public static string GetFirstTag(string tags)
        {
            string firstTag = tags;

            int spaceIndex = tags.IndexOf(' ');

            if (spaceIndex >= 0)
            {
                firstTag = tags.Substring(0, spaceIndex);
            }

            if (firstTag.Contains("|") || firstTag.Length == 0)
            {
                return null;
            }

            return firstTag.ToLowerInvariant();
        }
    }
}
